# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import gauge
import os


def Tool_PlotRainfallEvent(dat, year):
    # extract the data in year
    gauges = gauge.Read(dat, 229)
    subset = gauges[gauges.index == year]
    subset = gauge.Clean(subset)

    month = {1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30,
             7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
    # calculate days of February
    if year % 4 == 0:
        month[2] = 29
    else:
        month[2] = 28

    # gauge50Loc = [10, 15, 22, 26, 38, 41, 43, 49, 60, 61, 62, 64, 66, 77, 89,
    #               90, 92, 93, 94, 98, 100, 108, 109, 114, 124, 126, 127, 128,
    #               129, 132, 140, 142, 164, 167, 170, 174, 175, 177, 178, 181,
    #               205, 212, 219]
    gauge50Loc = [10, 13, 15, 22, 26, 38, 41, 43, 49, 60, 61, 62, 64, 66, 77,
                  89, 90, 92, 93, 94, 98, 100, 107, 108, 109, 114, 124, 126,
                  127, 128, 129, 132, 138, 140, 142, 164, 167, 170, 174, 175,
                  177, 178, 181, 204, 205, 206, 212, 219, 220, 230]
    # gauge50 = subset.iloc[:, 26]
    # mean = gauge50
    gauge50 = subset.iloc[:, gauge50Loc]
    mean = np.mean(gauge50, axis=1)
    for m in month:
        if m == 1:
            gauge_data = mean[:(24 * month[1] + 1)]
        else:
            bef_days = np.sum([month[i] for i in range(1, m)])
            aft_days = np.sum([month[i] for i in range(1, m + 1)])
            gauge_data = mean[(24 * bef_days + 1):(24 * aft_days + 1)]

        # plot precipitation
        time = np.arange(len(gauge_data))
        plt.figure(figsize=(10, 10))
        plt.xlabel('Time')
        plt.ylabel('Precipitation')
        plt.grid(True)
        plt.title('month ' + str(m))
        plt.bar(time, gauge_data, width=0.2, facecolor='lightskyblue')
        plt.xticks(np.arange(month[m] + 1) * 24, np.arange(1, month[m] + 1))
        output_path = r'F:/research/rainfall_estimation/result/rainfall_events/' + \
            str(year) + '/'
        if not os.path.exists(output_path):
            os.makedirs(output_path)
        result = output_path + str(m) + r'.jpg'
        plt.savefig(result)
    plt.show()


if __name__ == "__main__":
    Tool_PlotRainfallEvent(
        r"F:/research/rainfall_estimation/dat/Gauge/Gauge229_07_10_1h.dat", 2008)
